<template>
  <div class="myDialog">
    <!-- 弹窗组件 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="title"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      width="1000px">
      <el-row :gutter="12">
        <el-col :span="8">
          <div class="tree-box">
            <el-card shadow="never">
              <el-tree
                ref="tree"
                :data="treeData"
                :props="defaultProps"
                :default-checked-keys="checkedKeys"
                :expand-on-click-node="false"
                check-on-click-node
                show-checkbox
                default-expand-all
                check-strictly
                node-key="id"
                @check="checkChange"
              />
            </el-card>
          </div>
        </el-col>
        <el-col :span="16">
          <!-- <dynForm
          ref="dataForm"
          :info-form="form"
          :search-tags="searchTags"
          :select-list="selectList"
          :rules="rules"
        /> -->
          <el-form ref="dataForm" :model="form" :rules="rules" label-width="120px">
            <!-- <el-form-item :label="$t('userGroupName')" prop="name">
              <el-input v-model="form.name" />
            </el-form-item> -->
            <el-form-item :label="$t('deptName')" :style="{lineHeight: '22px'}">
              <treeselect
                :multiple="false"
                :disabled="form.id? true: false"
                :options="options"
                v-model="form.name"
                :placeholder="`${$t('pleaseSelect')}${$t('deptName')}`"
                :no-children-text="$t('noMoreData')"
                :no-options-text="$t('noMoreData')"
                :no-results-text="$t('noMoreData')"
                @select="getUserList"
              />
            </el-form-item>
            <el-form-item :label="$t('selectusers')" prop="userIds">
              <el-select v-model="form.userIds" multiple>
                <el-option
                  v-for="item of userIdsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <!-- <el-form-item :label="$t('equipmentLevel')" :style="{lineHeight: '22px'}">
              <treeselect
                :multiple="true"
                :options="options"
                v-model="form.eqpIds"
                :placeholder="`${$t('pleaseSelect')}${$t('selectParent')}`"
                :no-children-text="$t('noMoreData')"
                :no-options-text="$t('noMoreData')"
                :no-results-text="$t('noMoreData')"
                value-consists-of="ALL"
              />
            </el-form-item> -->
            <el-form-item :label="$t('description')">
              <el-input
                :rows="3"
                v-model="form.description"
                maxlength="200"
                show-word-limit
                type="textarea"/>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button icon="el-icon-circle-close" @click="closeDialog">{{
          $t("cancel")
        }}</el-button>
        <el-button v-btnThrottle="doSave" type="primary" icon="el-icon-receiving">{{ this.$t('save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import usergroupApi, { getUserIdGroups } from '@/api/system/usergroup'
import { getAllProjectUsers } from '@/api/system/user'
import { getTreeChildList } from '@/api/equipment/prodTreeNode'
import mySetting from '@/mixins/mySetting'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getTreeList as getDeptTreeList } from '@/api/equipment/prodTreeNode'
import { getTreeList } from '@/api/system/dept'

export default {
  name: 'UserGroupModel',
  components: { Treeselect },
  mixins: [mySetting],
  data() {
    return {
      title: '',
      form: {
        userIds: []
      },
      selectList: {},
      userIdsList: [],
      options: [],
      checkedKeys: [],
      dialogFormVisible: false,
      rules: {
        userIds: [
          { required: true, message: `${this.$t('pleaseInput')}${this.$t('userGroupName')}`, trigger: 'change' }
        ]
      }, // 表单校验规则
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    // 新增数据
    doSave() {
      if (this.validForm()) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const ids = this.$refs.tree.getCheckedKeys()
            if (this.form.id) {
              // 存在id则是更新
              usergroupApi.edit(this.$clearNull({ ...this.form, eqpIds: ids })).then(res => {
                this.$betterTips(res, this.closeDialog, this.handleUpdate)
              })
            } else {
              // 不存在id则是新增
              usergroupApi.add(this.$clearNull({ ...this.form, eqpIds: ids })).then(res => {
                this.$betterTips(res, this.closeDialog, this.handleUpdate)
              })
            }
          }
        })
      }
    },

    async getDeptList() {
      const res = await getTreeList()
      const formatTree = (root) => {
        return (root || []).map(node => {
          const { id, name, children } = node
          return {
            id,
            label: name,
            children: formatTree(children)
          }
        })
      }
      this.options = formatTree(res.data)
    },

    getUserList(node) {
      this.form.userIds = []
      getUserIdGroups({ deptId: node.id }).then(res => {
        this.userIdsList = res.data
      })
    },

    // 打开弹窗
    async openDialog(row) {
      if (row && row.id) {
        this.title = this.$t('modify')
        usergroupApi.get({ id: row.id }).then(res => {
          this.form = res.data
          getUserIdGroups({ deptId: res.data.name }).then(res => {
            this.userIdsList = res.data
          })
          this.checkedKeys = res.data.eqpIds
          this.$refs.tree.setCheckedKeys(res.data.eqpIds)
        })
      } else {
        this.title = this.$t('add')
      }
      // this.getAllProjectUsers()
      // this.geteqpIdsList()

      this.getDeptList()
      this.dialogFormVisible = true
      const data = await getDeptTreeList({ check: 0, addEqp: 1 })
      this.treeData = data.data
      // this.options = formatTree(data.data)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 关闭弹窗
    closeDialog() {
      this.$refs.tree.setCheckedKeys([])
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleUpdate() {
      this.$emit('initList')
    },

    validForm() {
      const ids = this.$refs.tree.getCheckedKeys()
      if (!ids.length) {
        this.$notify.error({
          message: '请选择设备'
        })
        return false
      } else {
        return true
      }
    },

    async getAllProjectUsers() {
      const res = await getAllProjectUsers()
      this.userIdsList = res.data
    },
    async geteqpIdsList() {
      const res = await getTreeChildList()
      this.$set(this.selectList, 'eqpIds', res.data)
    },
    checkChange(data) {
      if (this.checkedKeys.includes(data.id)) {
        const child = [data.id].concat(this.flatten(data.children))
        for (let i = 0; i < child.length; i++) {
          const index = this.checkedKeys.indexOf(child[i])
          if (index !== -1) {
            this.checkedKeys.splice(index, 1)
          }
        }
      } else {
        const child = [data.id].concat(this.flatten(data.children))
        for (let i = 0; i < child.length; i++) {
          const index = this.checkedKeys.indexOf(child[i])
          if (index === -1) {
            this.checkedKeys.push(child[i])
          }
        }
      }
      this.$refs.tree.setCheckedKeys(this.checkedKeys)
    },
    flatten(tree) {
      return (tree || []).reduce((total, current) => {
        const { children, id } = current
        return total.concat(id, this.flatten(children))
      }, [])
    }
  }
}
</script>
<style lang="scss" scoped>
.el-select{
  width: 100%;
}
::v-deep .vue-treeselect__value-container{
      line-height: 20px;
}
::v-deep .vue-treeselect__multi-value-item{
    background-color: #f4f4f5;
    border-color: #e9e9eb;
    color: #909399;

    .vue-treeselect__value-remove{
      // background-color: #c0c4cc;
      color: #909399;
      border: none;
      // border-radius: 50%;
      // transform: scale(.8);
      // width: 18px;
      // height: 20px;
      // line-height: 16px;
      // vertical-align: middle;;
      // display: flex;
      // justify-content: center;
      // align-items: center;
    }
}
.tree-box{
  width: 100%;
  height: 600px;
  overflow-y: auto;
}
</style>
